package cn.jiedh.app.meiweidk.mine;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.authreal.api.AuthBuilder;
import com.authreal.api.OnResultListener;
import com.authreal.component.AuthComponentFactory;
import com.authreal.component.OCRComponent;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.DeviceUtils;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.LoadUtils;
import cn.jiedh.app.meiweidk.Utils.tool.Md5;
import cn.jiedh.app.meiweidk.Utils.tool.StringUtil;
import cn.jiedh.app.meiweidk.Utils.tool.StringUtils;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.app.MyApp;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.entity.IdCardBean;
import cn.jiedh.app.meiweidk.entity.UserInfoBean;

/**
 * @name：
 * @author：彭鑫
 * @email：pengwwe457621023@qq.com
 * @createTime：2018/11/17
 */

public class AuthenActivity extends BaseActivity {

    @BindView(R.id.ocr_iv)
    ImageView ocr_iv;

    @BindView(R.id.username_tv)
    TextView username_tv;
    @BindView(R.id.idcard_tv)
    TextView idcard_tv;

    private IdCardBean idCardBean;


    private UserInfoBean userInfoBean = new UserInfoBean();//参数集合


    @Override
    protected int getLayoutView() {
        return R.layout.activity_authen;
    }

    @Override
    protected void initView(View view) {
        setTitle("实名认证");
    }

    @Override
    protected void initData() {
        MyApp.getInstance().addActivity(this);
//        initPersonInfo(str);
    }


    @OnClick({R.id.authen_next, R.id.ocr_iv})
    public void Click(View v) {
        switch (v.getId()) {
            case R.id.authen_next:
                if (!StringUtil.isEmpty(userInfoBean.getUsername())) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("userinfo", userInfoBean);
                    ActivityUtil.next(this, BasicInfoActivity.class, bundle);
                } else {
                    T.show("请先扫描确认身份信息");
                }

                break;

            case R.id.ocr_iv:
                startOCR();
                break;
        }
    }


    /**
     * 开始身份证扫描
     */
    private void startOCR() {
        OCRComponent ocrComponent = AuthComponentFactory.getOcrComponent();
        ocrComponent.showConfirm(true);
        getAuthBuilder().addFollow(ocrComponent).start(this);
    }

    /**
     * 获取AuthBuilder。
     * 请在每次调用前获取新的AuthBuilder
     * 一个AuthBuilder 不要调用两次start()方法
     *
     * @return
     */
    private AuthBuilder getAuthBuilder() {

        // 订单号商户自己生成：不超过36位，非空，不能重复
        String partner_order_id = "orider_123123";
        //商户pub_key ： 开户时通过邮件发送给商户
        String pubKey = "ef479a69-404c-400b-8cd8-d1d67f0fc7e8";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        //签名时间：有效期5分钟，请每次重新生成 :签名时间格式：yyyyMMddHHmmss
        String sign_time = simpleDateFormat.format(new Date());
        // 商户 security_key  ：  开户时通过邮件发送给商户
        String security_key = "4f3c8e83-fc72-4478-95bc-12462df50901";
        // 签名规则
        String singStr = "pub_key=" + pubKey + "|partner_order_id=" + partner_order_id + "|sign_time=" + sign_time + "|security_key=" + security_key;
        //生成 签名
        String sign = Md5.encrypt(singStr);
        /** 以上签名 请在服务端生成，防止key泄露 */

        AuthBuilder authBuilder = new AuthBuilder(partner_order_id, pubKey, sign_time, sign, (op_type, result) -> {
            Log.e("MainActivity:result", op_type + "//" + result);
            try {
                JSONObject jsonObject = new JSONObject(result);
                /***
                 * 业务处理成功（不是认证成功）
                 */
                if (jsonObject.has("success") && jsonObject.getString("success").equals("true")) {
                    /** 业务处理成功 ，可以根据不同的模块 处理数据 */
                    switch (op_type) {
                        case AuthBuilder.OPTION_ERROR:
                            //// TODO:  error
                            break;
                        case AuthBuilder.OPTION_OCR:
                            //// TODO:  OCR扫描 回调
                            initPersonInfo(result);
                            L.i(result);
                            break;
                    }
                } else {
                    /***
                     * 业务处理失败
                     */
                    String message = jsonObject.getString("message");
                    String errorcode = jsonObject.getString("errorcode");
                    /** 打印错误日志，可根据文档定位问题 */
                    Log.d("MainActivity", errorcode + ":" + message);


                    T.show("扫描失败，请在明亮环境下重试");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        });

        return authBuilder;
    }

    /**
     * 处理扫描到的用户信息
     * @param result
     */
    private void initPersonInfo(String result){
        idCardBean = new Gson().fromJson(result, IdCardBean.class);

        username_tv.setText(idCardBean.getId_name());
        idcard_tv.setText(idCardBean.getId_number());
        LoadUtils.loadImage(AuthenActivity.this, idCardBean.getIdcard_front_photo(), ocr_iv);

        userInfoBean.setUsername(idCardBean.getId_name());
        userInfoBean.setIdCard(idCardBean.getId_number());
    }

    String str="{\"address\":\"重庆市彭水县普子镇石坝子村9组117号\",\"age\":\"25\",\"birthday\":\"1993.03.06\",\"classify\":\"2\",\"gender\":\"男\",\"id_name\":\"黄桂红\",\"id_number\":\"500243199303061872\",\"idcard_back_photo\":\"https:\\/\\/idsafe-auth.udcredit.com\\/front\\/4.0\\/api\\/file_download\\/platform\\/web?name=i_20181121103404143860270.jpg&param=8664FD3F90B283E4626DA3FD54132AF763E26115F9A34944F61A2BF46695D6\",\"idcard_front_photo\":\"https:\\/\\/idsafe-auth.udcredit.com\\/front\\/4.0\\/api\\/file_download\\/platform\\/web?name=i_20181121103330276023792.jpg&param=8664FD3F90B283E4626DA3FD54132AF763E26116FEA24F4CFD1D2CFA6F96DF\",\"idcard_portrait_photo\":\"https:\\/\\/idsafe-auth.udcredit.com\\/front\\/4.0\\/api\\/file_download\\/platform\\/web?name=i_20181121103330659958348.jpg&param=8664FD3F90B283E4626DA3FD54132AF763E26116FEA24F4CFD1D2CFA6F96DF\",\"issuing_authority\":\"彭水苗族土家族自治县公安局\",\"nation\":\"苗\",\"partner_order_id\":\"orider_123123\",\"validity_period\":\"2015.05.28-2025.05.28\",\"validity_period_expired\":\"0\",\"message\":\"操作成功\",\"session_id\":\"391658110693539849\",\"success\":\"true\"}\n";
}



